package cbfg.http.demo.wanandroid

import androidx.lifecycle.Lifecycle
import cbfg.http.demo.LifecycleUtils
import cbfg.http.demo.wanandroid.entity.BaseWanEntity
import cbfg.http.subscribe.Disposable
import cbfg.http.subscribe.Observer

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/21 13:57
 * 功能描述:
 */
abstract class WanObserver<T : Any>(
    private val lifecycle: Lifecycle? = null,
    private val endEvent: Lifecycle.Event = Lifecycle.Event.ON_DESTROY
) : Observer<T> {

    abstract fun onSuccess(result: T)

    override fun onSubscribe(disposable: Disposable) {
        lifecycle?.run { LifecycleUtils.bindUntil(this, endEvent, disposable) }
    }

    override fun onNext(entity: T) {
        when {
            entity !is BaseWanEntity<*> -> onSuccess(entity)
            entity.isSuccessful() -> onSuccess(entity)
            else -> onError(Throwable(entity.errorMsg))
        }
    }
}